<?php
class Controller_Channel extends  Controller_Template {
	public function __construct($req, $res) {
		$this->template = "smarty:channel/channels";
		parent::__construct($req, $res);
	}

    public function action_index ()
    {
        $this->action_all();
    }

	/**
	 *
	 * 获得所有的推广活动
	 *
	 */

	public function action_all()
	{
        if (site::type() != 'manager')
        {
            $this->merchant_channels();
            return;
        }

        $role_id = user::current_user()->get_role_id();
        $query   = $this->request->query();
        $manager = Arr::get($query, 'manager',  0);
        $activity= Arr::get($query, 'activity', 0);
        $merchant= Arr::get($query, 'merchant', NULL);
        $chnkey  = Arr::get($query, 'chnkey', NULL);
        $activity_ids = array($activity);

        if ($role_id == 'auditor')
        {
            $manager = user::current_user_id();
        }
        else if ($role_id == 'commonmanager' or $role_id == 'supermanager')
        {
        }

        $activities = Promotion_Activity::get_activities(NULL, $manager);
        $actids = array();
        foreach ($activities as & $a)
        {
            $actids[] = Arr::get($a, 'id', 0);
        }

        if (in_array($activity, $actids) && $activity > 0)
            $activity_ids = array($activity);
        else if (empty($activity))
            $activity_ids = $actids;

        $cids     = $this->channel_ids ($activity_ids, $merchant, $chnkey);
		$channels = Promotion_Channel::channels($cids, $merchant, $include_roi = TRUE);
		$this->template->set('channels',$channels);
	}



    public function action_detail ($channel_id)
    {
        $chnid = (int) $channel_id;
        $this->template->set_filename('smarty:channel/detail');
        $this->template->set('channel', Promotion_Channel::info($chnid));
    }

    public function action_roi ($channel_id)
    {
        $chnid = (int) $channel_id;
        $this->template->set_filename('smarty:channel/ROI');
        $this->template->set('channel', Promotion_Channel::info($chnid));
        $this->template->set('roi_list', Promotion_Channel_ROI::lists($chnid));
    }

	public function action_add()
	{
		$mer_id = User::current_user_id();
		$this->template->set_filename('smarty:channel/add_channel');
        $this->template->set('channel_prefix', Kohana::config('tuiguang.channel.prefix'));
	}

	public function action_add_submit()
	{
		$mer_id = User::current_user_id();
		$channel_name = $this->request->post('channel_name',NULL);
		$channel_key= $this->request->post('channel_key',NULL);
		$channel_desc= $this->request->post('channel_desc',NULL);

		if($channel_name != NULL && $channel_key != NULL && $channel_desc != NULL)
		{
            try {
                $unique_key = Kohana::config('tuiguang.channel.prefix').$channel_key;
                if (Promotion_Channel::has_channel($unique_key))
                    throw new Exception_Empty("渠道标识符重复, 请重新起名");

			    $channels = Promotion_Channel::add($channel_name,$unique_key,$channel_desc,$mer_id);
			    $this->request->redirect('/channel/');
            }
            catch (Exception_Empty $e)
            {
		        $this->template->set_filename('smarty:channel/add_channel');
                $this->template->set('alert_message', $e->getMessage());
                $channel = array(
                    'name'        => $channel_name,
                    'unique_key'  => $channel_key,
                    'description' => $channel_desc,
                );
                $this->template->set('channel', $channel);
                $this->template->set('channel_prefix', Kohana::config('tuiguang.channel.prefix'));
            }
		}else{
			$this->request->redirect('/channel/add');
		}
	}

    public function action_change_activity ($channel_id)
    {
        $this->template->set('channel', Promotion_Channel::info($channel_id));
        $this->template->set_filename("smarty:channel/chgactivity");
        $post  = $this->request->post();
        $chnid = (int) $channel_id;
        $actid = Arr::get($post, 'activity_id', 0);

        if (empty($actid))
        {
            $ids  = Promotion_Activity::activity_ids ('CPA', 'newbie', 0);
            $acts = Promotion_Activity::infos($ids);
            $this->template->set('acts', $acts);
            return;
        }
        else
        {
            try {

                if (empty($chnid) || empty($actid))
                    throw new Exception("渠道或者活动不可为空");

                Promotion_Channel::change_activity ($chnid, $actid);

                $this->template->set('alert_message', "渠道调整成功！");
            }
            catch(Exception $e)
            {
                $this->template->set('alert_message', $e->getMessage());
            }
        }
    }

    public function action_rename ()
    {
        $this->template->set_filename("smarty:channel/rename");
        $post = $this->request->post();

        if (empty($post))
        {
            return;
        }
        else
        {
            $chn_curr_key = trim(Arr::get($post, 'chn_curr_key'));
            $chn_next_key = trim(Arr::get($post, 'chn_next_key'));

            try {

                if (empty($chn_curr_key) || empty($chn_next_key))
                    throw new Exception("渠道标识不可为空");

                if ($chn_curr_key == $chn_next_key)
                    throw new Exception("渠道标识一致，拒绝修改");

                Promotion_Channel::rename_unique_key ($chn_curr_key, $chn_next_key);

                $this->template->set('alert_message', "渠道标识改名成功！");
            }
            catch(Exception $e)
            {
                $this->template->set('alert_message', $e->getMessage());
            }
        }
    }

    public function action_edit_ratio ($activity_id, $channel_id)
    {
        $this->template->set_filename('smarty:channel/ratio');
        $post = $this->request->post();


        if (! empty($post))
        {
            $ratio       = (int) Arr::get($post, 'ratio');
            $promotion = new Promotion($activity_id, $channel_id);
            $promotion->ratio($ratio);
            $this->template->set('alert_message', '调整系数成功！');
        }
        
        $this->template->set('promotion', Promotion::info($activity_id, $channel_id, TRUE));
    }

	public function action_import_all_roi()
	{
		$day = date('Ymd');
		$rs = Promotion_Channel_ROI_Import::all();
		foreach($rs->data as $val)
		{
			$channel_key = $val->channelName;
			$um_add_user = $val->umAddUser;
			$promotion_cost = $val->promotionCost;
			$total_down = $val->totalDown;
			$ppc_ad_down = $val->ppcAdDown;
			$promotion_ad_down = $val->promotionAdDown;
			$start_day = $val->startDay;
			$total_in_come = $val->totalInCome;
			$roi = $val->roi;
			$flag = 1;
			$insert_rs = Promotion_Channel_ROI::insert_roi($day,$channel_key,$channel_id,$um_add_user,$promotion_cost,$total_down,$ppc_ad_down,$promotion_ad_down,$start_day,$end_day,$total_in_come,$roi,$flag);
		}
	}
	public function action_import_stage_roi($day = NULL)
	{
		if($day == NULL)
		{
			$day = date('Ymd');
		}
		$rs = Promotion_Channel_ROI_Import::stage($day);
		foreach($rs->data as $val)
		{
			$channel_key = $val->channelName;
			$um_add_user = $val->umAddUser;
			$promotion_cost = $val->promotionCost;
			$total_down = $val->totalDown;
			$ppc_ad_down = $val->ppcAdDown;
			$promotion_ad_down = $val->promotionAdDown;
			$start_day = $val->startDay;
			$end_day = $val->endDay;
			$total_in_come = $val->totalInCome;
			$roi = $val->roi;
			$flag = 2;
			$insert_rs = Promotion_Channel_ROI::insert_roi($day,$channel_key,$channel_id,$um_add_user,$promotion_cost,$total_down,$ppc_ad_down,$promotion_ad_down,$start_day,$end_day,$total_in_come,$roi,$flag);
		}
	}

    protected function merchant_channels ()
    {
		$channels = Promotion_Channel::channels(NULL, user::current_user_id());
		$this->template->set('channels',$channels);
    }


    protected function channel_ids ($activity_ids, $merchant_id, $chnkey = NULL)
    {
        $query = array(
            'status' => Kohana::config('tuiguang.activity_channel.status.verified'),
            'unique_key'          => $chnkey,
            'enable_search_count' => FALSE,
            'format_results'      => FALSE,
        );

        if (! empty($activity_ids))
            $query['activity'] = $activity_ids;

        if (! empty($merchant_id))
            $query['merchant'] = $merchant_id;


        $channels = array();
        $result   = Promotion::search($query, NULL, NULL);
        foreach ($result['list'] as $rs)
            $channels[] = $rs['channel_id'];
        
        $channels = array_unique($channels);
        if (empty($channels))
            return array(-1);
        else
            return $channels;
    }
}
